package com.huhao.wshare.Friends;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.imageview.ShapeableImageView;
import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.Dynamic.FriendDynamicActivity;
import com.huhao.wshare.R;

import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

import static com.huhao.wshare.Config.BASE_URL;
import static com.huhao.wshare.Config.GET_USER_PROFILE_API;

public class FriendActivity extends BaseActivity {
    private TextView tvUsername, tvAccount, tvSigns, tvRemark;
    private TextView tvEmail, tvPhone;
    private ImageView ivGender;
    private ShapeableImageView ivAvatar;
    private ImageView ivBackground;
    private LinearLayout llMomentsEntry;
    private OkHttpClient client = new OkHttpClient();
    private String token;
    private int friendId;
    private String avatarUrl;
    private String bkImgUrl;
    private String gender;
    private ImageButton btnMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend);

        // 获取传递的friendId
        friendId = getIntent().getIntExtra("friendId", -1);
        String friendRemark = getIntent().getStringExtra("remark");
        // 从SharedPreferences获取token
        token = getSharedPreferences("user_prefs", MODE_PRIVATE).getString("token", null);

        // 初始化视图
        initViews();

        if (friendRemark != null && !friendRemark.isEmpty()) {
            tvRemark.setText("备注：" + friendRemark);
        } else {
            tvRemark.setText("备注：");
        }

        // 获取好友信息
        fetchFriendProfile();

        // 设置动态空间入口点击事件
        setupMomentsEntry();

        setupMenuButton();
    }

    private void initViews() {
        tvUsername = findViewById(R.id.tvUsername);
        tvAccount = findViewById(R.id.tvAccount);
        tvSigns = findViewById(R.id.tvSigns);
        ivAvatar = findViewById(R.id.ivAvatar);
        tvRemark = findViewById(R.id.tvRemark);
        ivBackground = findViewById(R.id.background_image);
        ivGender = findViewById(R.id.ivGender);
        llMomentsEntry = findViewById(R.id.ll_moments_entry);
        tvEmail = findViewById(R.id.tvEmail);
        tvPhone = findViewById(R.id.tvPhone);
        btnMenu = findViewById(R.id.btn_menu);
    }

    private void fetchFriendProfile() {
        if (friendId == -1 || token == null) {
            Toast.makeText(this, "无法获取用户信息", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 构建请求头，包含Authorization
        Request request = new Request.Builder()
                .url(GET_USER_PROFILE_API + "/" + friendId)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送网络请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> Toast.makeText(FriendActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String respStr = response.body() != null ? response.body().string() : "";
                    runOnUiThread(() -> handleProfileResponse(respStr));
                } else {
                    runOnUiThread(() -> Toast.makeText(FriendActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void setupMenuButton() {
        btnMenu.setOnClickListener(v -> {
            PopupMenu popup = new PopupMenu(FriendActivity.this, v);
            popup.getMenuInflater().inflate(R.menu.menu_friend_options, popup.getMenu());

            popup.setOnMenuItemClickListener(item -> {
                int id = item.getItemId();
                if (id == R.id.menu_edit_remark) {
                    showEditRemarkDialog();
                    return true;
                } else if (id == R.id.menu_delete_friend) {
                    showDeleteConfirmDialog();
                    return true;
                }
                return false;
            });
            popup.show();
        });
    }

    private void showEditRemarkDialog() {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("修改备注");

        final EditText input = new EditText(this);
        input.setHint(tvRemark.getText().toString().replace("备注：", ""));
        builder.setView(input);

        builder.setPositiveButton("确定", (dialog, which) -> {
            String newRemark = input.getText().toString().trim();
            // 修改：允许空字符串，传递null来清除备注
            if (newRemark.isEmpty()) {
                newRemark = null;
            }
            editFriendRemark(newRemark);
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void editFriendRemark(String newRemark) {
        JSONObject json = new JSONObject();
        try {
            json.put("remark", newRemark);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Request request = new Request.Builder()
                .url(BASE_URL + "/api/friends/" + friendId + "/remark")
                .patch(RequestBody.create(json.toString(), MediaType.parse("application/json")))
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> Toast.makeText(FriendActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String respStr = response.body() != null ? response.body().string() : "";
                runOnUiThread(() -> {
                    try {
                        JSONObject json = new JSONObject(respStr);
                        if (json.getInt("code") == 200) {
                            // 修改：处理返回的备注信息，支持null值
                            String remark = json.getString("remark");
                            if (remark == null || remark.equals("null")) {
                                tvRemark.setText("备注：");
                                // 清除SharedPreferences中的备注
                                getSharedPreferences("friend_remarks", MODE_PRIVATE)
                                        .edit()
                                        .remove(String.valueOf(friendId))
                                        .apply();
                            } else {
                                tvRemark.setText("备注：" + remark);
                                // 保存到SharedPreferences
                                getSharedPreferences("friend_remarks", MODE_PRIVATE)
                                        .edit()
                                        .putString(String.valueOf(friendId), remark)
                                        .apply();
                            }
                        } else {
                            Toast.makeText(FriendActivity.this, json.optString("message", "修改备注失败"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        Toast.makeText(FriendActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void showDeleteConfirmDialog() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("删除好友")
                .setMessage("确定要删除该好友吗？此操作不可逆！")
                .setPositiveButton("删除", (dialog, which) -> deleteFriend())
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteFriend() {
        Request request = new Request.Builder()
                .url(BASE_URL + "/api/friends/" + friendId)
                .delete()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> Toast.makeText(FriendActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String respStr = response.body() != null ? response.body().string() : "";
                runOnUiThread(() -> {
                    try {
                        JSONObject json = new JSONObject(respStr);
                        if (json.getInt("code") == 200) {
                            // 清除本地备注缓存
                            getSharedPreferences("friend_remarks", MODE_PRIVATE)
                                    .edit()
                                    .remove(String.valueOf(friendId))
                                    .apply();

                            Toast.makeText(FriendActivity.this, "好友删除成功", Toast.LENGTH_SHORT).show();
                            finish(); // 关闭当前页面
                        } else {
                            Toast.makeText(FriendActivity.this, json.optString("message", "删除失败"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        Toast.makeText(FriendActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void handleProfileResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                JSONObject data = json.optJSONObject("data");
                if (data != null) {
                    // 更新UI组件
                    tvUsername.setText(data.optString("username"));
                    tvAccount.setText("wshare账号：" + data.optString("account"));
                    tvSigns.setText(data.optString("signs") != null ? data.optString("signs") : "暂无个性签名");
                    tvEmail.setText(data.optString("email"));
                    tvPhone.setText(data.optString("phone"));

                    // 设置头像
                    avatarUrl = data.optString("avatar");
                    int defaultAvatarResId = "woman".equals(data.optString("gender")) ?
                            R.drawable.default_avatar_woman : R.drawable.default_avatar_man;

                    if (!data.isNull("avatar") && !avatarUrl.isEmpty()) {
                        Glide.with(this)
                                .load(avatarUrl)
                                .apply(RequestOptions.circleCropTransform())
                                .placeholder(defaultAvatarResId)
                                .error(defaultAvatarResId)
                                .into(ivAvatar);
                    } else {
                        ivAvatar.setImageResource(defaultAvatarResId);
                    }

                    // 设置背景图
                    bkImgUrl = data.optString("bkImg");
                    if (!data.isNull("bkImg") && !bkImgUrl.isEmpty()) {
                        Glide.with(this)
                                .load(bkImgUrl)
                                .into(ivBackground);
                    } else {
                        ivBackground.setImageResource(R.drawable.default_background);
                    }

                    // 设置性别图标
                    gender = data.optString("gender");
                    if ("man".equals(gender)) {
                        ivGender.setImageResource(R.drawable.ic_male);
                        ivGender.setVisibility(View.VISIBLE);
                    } else if ("woman".equals(gender)) {
                        ivGender.setImageResource(R.drawable.ic_female);
                        ivGender.setVisibility(View.VISIBLE);
                    } else {
                        ivGender.setVisibility(View.GONE);
                    }
                }
            } else {
                Toast.makeText(this, json.optString("message"), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "解析用户信息失败", Toast.LENGTH_SHORT).show();
            Log.e("FriendActivity", "解析JSON失败", e);
        }
    }

    private void setupMomentsEntry() {
        llMomentsEntry.setOnClickListener(v -> {
            Intent intent = new Intent(FriendActivity.this, FriendDynamicActivity.class);
            intent.putExtra("friendId", friendId);
            intent.putExtra("username", tvUsername.getText().toString());
            intent.putExtra("avatarUrl", avatarUrl);
            intent.putExtra("backgroundUrl", bkImgUrl);
            intent.putExtra("gender", gender);
            startActivity(intent);
        });
    }
}